import Cookies from "js-cookie";
import packageJson from "../../../package.json";
export default class cache {
  session = {
    setString: (key: string, value: string): boolean => {
      try {
        sessionStorage.setItem(this.defineKey(key), value);
        return true;
      } catch (e) {
        return false;
      }
    },
    getString: (key: string): string => {
      try {
        return sessionStorage.getItem?.(this.defineKey(key)) || '';
      } catch (e) {
        return '';
      }
    },
    setJson: (key: string, value: { [key: string]: any }): boolean => {
      try {
        sessionStorage.setItem(this.defineKey(key), JSON.stringify(value));
        return true;
      } catch (e) {
        return false;
      }
    },
    getJson: (key: string): { [key: string]: any } | null => {
      try {
        return JSON.parse(sessionStorage.getItem?.(this.defineKey(key)) || 'null');
      } catch (e) {
        return null;
      }
    },
  }
  local = {
    setString: (key: string, value: string): boolean => {
      try {
        localStorage.setItem(this.defineKey(key), value);
        return true;
      } catch (e) {
        return false;
      }
    },
    getString: (key: string): string => {
      try {
        return localStorage.getItem?.(this.defineKey(key)) || '';
      } catch (e) {
        return '';
      }
    },
    setJson: (key: string, value: { [key: string]: any }): boolean => {
      try {
        localStorage.setItem(this.defineKey(key), JSON.stringify(value));
        return true;
      } catch (e) {
        return false;
      }
    },
    getJson: (key: string): { [key: string]: any } | null => {
      try {
        return JSON.parse(localStorage.getItem?.(this.defineKey(key)) || 'null');
      } catch (e) {
        return null;
      }
    },
  }
  cookie = {
    setString: (key: string, value: string, config = {}): boolean => {
      try {
        Cookies.set(this.defineKey(key), value, config);
        return true;
      } catch (e) {
        return false;
      }
    },
    getString: (key: string): string => {
      try {
        return Cookies.get?.(this.defineKey(key)) || '';
      } catch (e) {
        return '';
      }
    },
    setJson: (key: string, value: { [key: string]: any }, config = {}): boolean => {
      try {
        Cookies.set(this.defineKey(key), JSON.stringify(value), config);
        return true;
      } catch (e) {
        return false;
      }
    },
    getJson: (key: string): { [key: string]: any } | null => {
      try {
        return JSON.parse(Cookies.get?.(this.defineKey(key)) || 'null');
      } catch (e) {
        return null;
      }
    },
  }
  defineKey(key:string) {
    return `${packageJson.name}_${packageJson.version}_${process.env.VUE_APP_ENV}_${key}`;
  }
}